package home_swiper

import (
	"errors"
	"hft/Database/admin/home_swiper"
	"hft/e"
	"hft/global"
	"hft/tools"

	"gorm.io/gorm"
)

// 添加轮播图
type HomeSwiper struct{}

func (*HomeSwiper) AddSwiper(swipers []*home_swiper.HomeSwiper, claims tools.BaseClaims) (err error) {
	err = global.OC_DB.Transaction(func(tx *gorm.DB) error {
		err = global.OC_DB.Where("city = ? AND type = ?", claims.Belong, swipers[0].Type).Unscoped().Delete(swipers).Error
		if err != nil {
			return errors.New(e.ErrorInfo)
		}
		for _, v := range swipers {
			v.City = claims.Belong
		}
		if len(swipers) != 0 {
			err = global.OC_DB.Create(&swipers).Error
			if err != nil {
				return errors.New(e.ErrorInfo)
			}
			return nil
		} else {
			return nil
		}

	})
	return err
}

// 获取轮播图
func (*HomeSwiper) List(cateType int, claims tools.BaseClaims) (list []*home_swiper.HomeSwiper, err error) {
	var swiperList = make([]*home_swiper.HomeSwiper, 0)
	global.OC_DB.Where("city = ? AND type = ?", claims.Belong, cateType).Find(&swiperList)
	return swiperList, nil
}

var HomeSwiperService = new(HomeSwiper)
